<template>
  <div id="app">
    <Header class="header" />
    <van-loading color="#1989fa" v-show="LOADING" class="loading" size="40"
      >加载中...</van-loading
    >
    <router-view class="view" v-show="!LOADING"></router-view>
    <!-- 回到顶部按钮 -->
    <span id="return_top" title="回到顶部">返回顶部</span>
  </div>
</template>

<script>
import Header from "@/components/Header.vue";
import { mapState } from "vuex";
export default {
  name: "app",
  computed: {
    ...mapState(["LOADING"]),
  },
  mounted() {
    //  回到顶部效果
    var obtn = document.getElementById("return_top"); //获取回到顶部按钮的ID
    var clientHeight = document.documentElement.clientHeight; //获取可视区域的高度
    var timer = null; //定义一个定时器
    var isTop = true; //定义一个布尔值，用于判断是否到达顶部
    // var osTop = document.documentElement.scrollTop || document.body.scrollTop;
    // if (osTop >= clientHeight) {
    //   //如果滚动高度大于可视区域高度，则显示回到顶部按钮
    //   obtn.style.display = "block";
    // } else {
    //   //否则隐藏
    //   obtn.style.display = "none";
    // }
    window.onscroll = function() {
      //滚动条滚动事件
      //获取滚动条的滚动高度
      var osTop = document.documentElement.scrollTop || document.body.scrollTop;

      if (osTop >= clientHeight) {
        //如果滚动高度大于可视区域高度，则显示回到顶部按钮
        obtn.style.display = "block";
      } else {
        //否则隐藏
        obtn.style.display = "none";
      }
      //主要用于判断当 点击回到顶部按钮后 滚动条在回滚过程中，若手动滚动滚动条，则清除定时器
      if (!isTop) {
        clearInterval(timer);
      }
      isTop = false;
    };
    obtn.onclick = function() {
      //回到顶部按钮点击事件
      //设置一个定时器
      timer = setInterval(function() {
        //获取滚动条的滚动高度
        var osTop =
          document.documentElement.scrollTop || document.body.scrollTop;
        //用于设置速度差，产生缓动的效果
        var speed = Math.floor(-osTop / 6);
        document.documentElement.scrollTop = document.body.scrollTop =
          osTop + speed;
        isTop = true; //用于阻止滚动事件清除定时器
        if (osTop == 0) {
          clearInterval(timer);
        }
      }, 30);
      // }
    };
  },
  components: { Header },
};
</script>

<style scope>
#app {
  position: relative;
  padding-top: 80px;
}
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}
#return_top {
  width: 24px;
  box-sizing: content-box;
  color: gray;
  top: 389px;
  right: 30px;
  padding: 12px 5px 12px 15px;
  display: none;
  position: fixed;
  cursor: pointer;
  text-align: center;
  z-index: 100;
  background-color: #f5f5f5;
  border-radius: 12px 0 0 12px;
}
@media screen and (min-width: 600px) {
  .view {
    padding: 0 6%;
  }
}
.loading {
  font-size: 10px;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-10%);
}
</style>
